<?php


namespace App\Services;

/**
 * Class Menu 菜单业务类
 * @package App\Service
 */
class Menu extends BaseService
{
    /**
     * Menu constructor.
     */
    public function __construct()
    {
        $this->model = new \App\Models\Menu();
    }

    /**
     * getList 菜单列表
     * @param array $condition
     * @return array
     * @throws \Exception
     */
    public function getList(array $condition): array
    {
        try {
            if (request()->get('model') == 'all') {
                $list = $this->model->where($condition)->orderBy($this->model->listOrder,'desc')->get($this->model->listFields);
                foreach ($list as $key => $value) {
                    if ($list[$key]['is_directory'] == 1) {
                        $list[$key]['hasChildren'] = true;
                    } else {
                        $list[$key]['hasChildren'] = false;
                    }
                }
            } else {
                $list = $this->model->where($condition)
                    ->orderBy($this->model->listOrder,'desc')
                    ->paginate(request()->get('list_rows', 10), $this->model->listFields, 'page', request()->get('page', 1));
            }
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }

        return objectToArray($list);
    }

    /**
     * getDetailById 菜单详情
     * @param int $id
     * @return array
     * @throws \Exception
     */
    public function getDetailById(int $id): array
    {
        $result =  parent::getDetailById($id);
        if ($result) {
            $result['menus'] = explode('-', $result['paths']);
            foreach ($result['menus'] as $key => $value) {
                $result['menus'][$key] = (int)$result['menus'][$key];
                if (empty($result['menus'][$key])) {
                    unset($result['menus'][$key]);
                }
            }
            $result['menus'] = array_values($result['menus']);
        }

        return $result;
    }

    /**
     * getMenusTree 菜单树
     * @param array $condition
     * @return array
     */
    public function getMenusTree(array $condition): array
    {
        $menus = $this->model->where($condition)->get(['id', 'pid', 'name', 'title', 'level', 'is_directory'])->toArray();
        if (empty($menus)) {
            return [];
        }
        // 过滤没有子类的二级菜单
        foreach ($menus as $key => $value) {
            if ($menus[$key]['level'] == 2 && $menus[$key]['is_directory'] == 0) {
                unset($menus[$key]);
            }
        }

        return getTree(array_values($menus));
    }


}
